<template>
  <LoadPage :show="show"/>
  <view class="page">
    <Nav :bg-color="bgColor" class="nav">
      <!-- :style="{ 'max-width': 375 - capsule.barWidth + 'px' }" -->
      <view class="top-box dispaly-center">
        <view class="left dispaly-center" @click="$goUrl(`/subPackage/index/selectServer`)">
          <view class="name over-1" :style="{ color: textColor }">{{ serverItem.name ? serverItem.name : '选择服务点' }}
          </view>
          <view class="icon">
            <image src="/static/icon/down.png"/>
          </view>
        </view>
        <view class="middle">
          <view class="ipt">
            <input type="text" placeholder="请搜索" @click="$goUrl(`/subPackage/index/search`)">
            <view class="icon">
              <image src="/static/icon/search.png"/>
            </view>
          </view>
        </view>
        <button open-type="share" class="right">
          <view class="share dispaly-align-center">
            <image src="/static/icon/shra.png"/>
          </view>
        </button>

      </view>
    </Nav>
    <view class="content" :style="{ marginTop: navHeiht + 'px' }">
      <view class="swiper">
        <nut-swiper :init-page="0" :pagination-visible="false" pagination-color="#426543"
                    pagination-unselected-color="#808080" auto-play="3000">
          <nut-swiper-item v-for="item in bannerList" :key="item.id">
            <image :src="item.image" mode="aspectFill"/>
          </nut-swiper-item>
        </nut-swiper>
      </view>
      <view class="option">
        <!-- <nut-grid :border="false" square clickable>
        <nut-grid-item @click="clickCateItem(i)" :text="i.name" v-for="i in cateList" :key="i.id">
          <image :src="i.icon" mode="aspectFill" />
        </nut-grid-item>
      </nut-grid> -->
        <view class="op-list ">
          <view class="op-box">
            <view class="op-item" @click="clickCateItem(item)" v-for="(item, index) in cateList" :key="item.id">
              <view class="icon">
                <image :src="item.icon" mode="aspectFill"/>
              </view>
              <view class="n over-1">{{ item.name }}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="notice dispaly-just-between">
        <view class="desc dispaly-just-between w-100">
          <view class="left dispaly-center">
            <nut-swiper direction="vertical" height="30" :init-page="0" :pagination-visible="false"
                        pagination-color="#426543" pagination-unselected-color="#808080" auto-play="2000">
              <nut-swiper-item v-for="(item, index) in oneArray" :key="index">
                <view class="text dispaly-center" style="margin-right: 10rpx;">
                  <view class="t-n">{{ item.nick_name }}&nbsp;</view>
                  <view class="t-n">{{ item.total }}元 &nbsp; ，</view>
                </view>
              </nut-swiper-item>
            </nut-swiper>
            <nut-swiper direction="vertical" height="30" :init-page="0" :pagination-visible="false"
                        pagination-color="#426543" pagination-unselected-color="#808080" auto-play="2000">
              <nut-swiper-item v-for="(item, index) in twoArray" :key="index">
                <view class="text dispaly-center">
                  <view class="t-n">{{ item.nick_name }}&nbsp;</view>
                  <view class="t-n">{{ item.total }}元</view>
                </view>
              </nut-swiper-item>
            </nut-swiper>
          </view>
          <view class="right" @click="clickFx">
            分享赚佣金
            <!--            <image src="/static/image/fxs.png" mode="aspectFill" />-->
          </view>
        </view>
      </view>
      <view class="option">
        <!-- <nut-grid :border="false" square clickable>
        <nut-grid-item :text="i.name" v-for="i in optionListOne" :key="i.name">
          <image :src="i.url" mode="aspectFill" />
        </nut-grid-item>
      </nut-grid> -->

        <view class="op-list ">
          <view class="op-box">
            <button open-type="contact" class="b-item" v-for="i in optionListOne" :key="i.name">
              <view class="icon">
                <image :src="i.url" mode="aspectFill"/>
              </view>
              <view class="n over-1">{{ i.name }}</view>
            </button>
          </view>
        </view>
      </view>
      <view class="dispaly-just-between">
        <view class="project-box dispaly-just-between w-100">
          <view class="project ">
            <view class="title-box dispaly-just-between">
              <view class="dispaly-center t-left">
                <view class="line"></view>
                <view class="t-name">案例</view>
              </view>
              <view class="t-right dispaly-center" @click="$goUrl(`/subPackage/index/case`)">
                <view class="t-more">更多</view>
                <view class="t-icon dispaly-align-center">
                  <nut-icon size="10" custom-color="#e85b50" name="rect-right"></nut-icon>
                </view>
              </view>
            </view>
            <view class="pro-item dispaly-just-between">
              <view class="em" v-if="!caseList.length">
                <nut-empty image="empty" :image-size="74"></nut-empty>
              </view>
              <view v-else class="item" v-for="item in caseList" :key="item.id"
                    @click="$goUrl(`/subPackage/index/caseDetail?id=${item.id}`)">
                <view class="avatar">
                  <image :src="item.image" mode="aspectFill"/>
                </view>
                <view class="p-name over-1">{{ item.name }}</view>
                <!-- <view class="p-name over-1">{{ item.style }}</view> -->
              </view>
            </view>
          </view>
          <view class="project ">
            <view class="title-box dispaly-just-between">
              <view class="dispaly-center t-left">
                <view class="line"></view>
                <view class="t-name">在建项目</view>
              </view>
              <view class="t-right dispaly-center" @click="$goUrl(`/subPackage/index/proceedProject`)">
                <view class="t-more">更多</view>
                <view class="t-icon dispaly-align-center">
                  <nut-icon size="10" custom-color="#e85b50" name="rect-right"></nut-icon>
                </view>
              </view>
            </view>
            <view class="pro-item dispaly-just-between">
              <view class="em" v-if="!projectList.length">
                <nut-empty image="empty" :image-size="74"></nut-empty>
              </view>
              <view v-else class="item" v-for="item in projectList" :key="item.id"
                    @click="$goUrl(`/subPackage/index/projectOrderDetail?id=${item.id}`)">
                <view class="avatar">
                  <image :src="item.image" mode="aspectFill"/>
                </view>
                <view class="p-name over-1">{{ item.serviceName }}</view>
                <!-- <view class="p-name over-1">{{ item.specName }}</view> -->
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="project p">
        <view class="title-box dispaly-just-between">
          <view class="dispaly-center t-left">
            <view class="line"></view>
            <view class="t-name">推荐服务</view>
          </view>
          <view class="t-right dispaly-center" @click="skipServer">
            <view class="t-more">更多</view>
            <view class="t-icon dispaly-align-center">
              <nut-icon size="10" custom-color="#e85b50" name="rect-right"></nut-icon>
            </view>
          </view>
        </view>
        <view class="pro-item  pro">
          <view class="em" v-if="!serverList.length">
            <nut-empty image="empty" :image-size="74"></nut-empty>
          </view>
          <view v-else class="item " v-for="item in serverList" :key="item.id"
                @click="$goUrl(`/subPackage/server/serverDetail?id=${item.id}`)">
            <view class="avatar">
              <image :src="item.image" mode="aspectFill"/>
            </view>
            <view class="p-name over-1">{{ item.name }}</view>
            <view class="p-price over-1">¥{{ item.money.toFixed(2) }}</view>
          </view>
          <view class="dispaly-align-center w-100">
            <LoadMore :status="status"/>
          </view>
        </view>
      </view>
    </view>
  </view>
  <CustomerService/>
</template>

<script setup>
import {optionListOne} from '@/config/base'
import CustomerService from '@/components/customerService/customerService.vue'
import {ref, reactive, onMounted} from 'vue';
import {getBanner, getCategory, getZProject, getCase, reServer, updateUser, getFx, getServerList} from '@/api/apiList';
import {
  onLoad,
  onShow,
  onShareAppMessage,
  onShareTimeline,
  onPullDownRefresh,
  onReachBottom,
  onPageScroll
} from '@dcloudio/uni-app';
import {AMAP_KEY} from '@/config/base'
import {getElementHeight} from '@/utils/util'

const show = ref(true)
const capsule = uni.getStorageSync('capsule');

// 获取元素高度
const navHeiht = ref(0)
onMounted(async () => {
  const res = await getElementHeight('.nav')
  navHeiht.value = res
})

// 屏幕滚动
const bgColor = ref('#fff');
const textColor = ref('#000')
onPageScroll((res) => {
  const {scrollTop} = res;
  bgColor.value = scrollTop >= navHeiht.value ? '#e85b50' : '#fff';
  textColor.value = scrollTop >= navHeiht.value ? '#fff' : '#000';
})

// 点击option分类
const clickCateItem = (e) => {
  uni.setStorageSync('cateId', e.id)
  uni.reLaunch({
    url: `/pages/server/serverIndex?cId=${e.id}`
  })
}

let dataList = ref([])
let oneArray = ref([])
let twoArray = ref([])
const getList = async () => {
  const res = await getFx()
  if (res.code == 200) {
    dataList.value = res.data
    dataList.value.forEach(item => {
      item.nick_name = String(item.nick_name)
      item.nick_name = '**' + item.nick_name[item.nick_name.length - 1]
    })
    const {firstHalf, secondHalf} = splitArrayIntoTwoHalves(dataList.value)
    oneArray.value = firstHalf
    twoArray.value = secondHalf
  }
}

// 分割数组
const splitArrayIntoTwoHalves = (arr) => {
  const mid = Math.floor(arr.length / 2);
  const firstHalf = arr.slice(0, mid);
  const secondHalf = arr.slice(mid);
  return {firstHalf, secondHalf};
}

// 获取banner
const bannerList = ref([])
const getBannerList = async () => {
  return new Promise(async (resolve, reject) => {
    const res = await getBanner()
    if (res.code == 200) {
      bannerList.value = res.data
      resolve('ok')
    }
  })
}

// 获取类目
const cateList = ref([])
const getCateList = async () => {
  return new Promise(async (resolve, reject) => {
    const res = await getCategory()
    if (res.code == 200) {
      cateList.value = res.data
      resolve('ok')
    }
  })
}

// 获取在建项目
const projectList = ref([])
const getZProjectList = async () => {
  return new Promise(async (resolve, reject) => {
    const res = await getZProject()
    if (res.code == 200) {
      projectList.value = res.data
      resolve('ok')
    }
  })
}

// 获取案例
const caseList = ref([])
const getCaseList = async () => {
  return new Promise(async (resolve, reject) => {
    const res = await getCase()
    if (res.code == 200) {
      caseList.value = res.data
      resolve('ok')
    }
  })
}

// 获取服务
let serverQuery = reactive({
  pageNum: 1,
  pageSize: 16,
  categoryId: '',
  search: '',
  sort: 'asc',
  sortName: 'sort'
})
const serverList = ref([])
let status = ref('noMore')
const getServer = async () => {
  status.value = 'loading';
  return new Promise(async (resolve, reject) => {
    const res = await getServerList(serverQuery)
    if (res.code == 200) {
      if (res.rows.length) {
        serverList.value = [...serverList.value, ...res.rows]
        status.value = 'noMore'
        resolve('ok')
      } else {
        status.value = 'noMore'
      }
      resolve('ok')
    }
  })
}

onReachBottom(() => {
  serverQuery.pageNum++
  getServer()
})

// 成为分销商
const clickFx = () => {
  uni.reLaunch({
    url: `/pages/mine/mineIndex?isVisible=${true}`
  })
}

const init = async () => {
  const queue = [getBannerList(), getCateList(), getCaseList(), getServer(), getList(), getZProjectList()]
  const res = await Promise.all(queue)
  if (res.length) show.value = false
}

onPullDownRefresh(async () => {
  serverQuery.pageNum = 1
  serverList.value = []
  await uni.showLoading({
    title: '加载中'
  })
  bannerList.value = []
  caseList.value = []
  caseList.value = []
  serverList.value = []
  dataList.value = []
  projectList.value = []
  await init()
  uni.hideLoading()
  uni.stopPullDownRefresh()
})
// let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
// console.log(menuButtonInfo, 'menuButtonInfo')
onLoad(() => {
  init()
  if (uni.getStorageSync('token')) {
    getLocation()
  }
})

// 授权位置
const getLocation = () => {
  uni.getLocation({
    type: 'wgs84',
    success: function (res) {
      loadCity(res.longitude, res.latitude)
    }, fail(error) {
      uni.showToast({
        title: '您拒绝了授权',
        icon: 'none'
      })
    }
  })
}

const loadCity = (longitude, latitude) => {
  uni.request({
    header: {
      'Content-Type': 'application/text',
    },
    //注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
    url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude},${latitude}&key=${AMAP_KEY}`,
    success: async (res) => {
      const {addressComponent} = res.data.regeocode
      const address = addressComponent.city ?
          addressComponent.province + addressComponent.city + addressComponent.district
          : addressComponent.province + addressComponent.district
      if (uni.getStorageSync('token')) {
        await updateUser({userId: uni.getStorageSync('user').userId, address})
      }
      console.log(addressComponent, 'addressComponent')
    },
    fail(err) {
      console.log(err, "获取位置失败信息")
    }
  })
}

let serverItem = ref({})
onShow(() => {
  if (uni.getStorageSync('serverItem')) {
    serverItem.value = uni.getStorageSync('serverItem')
  }
})


// 前往更多服务
const skipServer = () => {
  uni.switchTab({
    url: '/pages/server/serverIndex'
  })
}

onShareAppMessage(() => {
  return {
    path: '/pages/index/index',
    title: '芒装商城'
  };
});

onShareTimeline(() => {
  return {
    path: '/pages/index/index',
    title: '芒装商城'
  };
});

</script>

<style lang="scss" scoped>
:deep(.nut-grid-item__content--clickable) {
  background-color: transparent;
}

:deep(.nut-empty) {
  padding: 0;
}

.nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.page {
  // height: 100vh;
  // display: flex;
  // flex-direction: column;
  // justify-content: space-between;
}

.pro {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .item {
    margin: 10rpx;
  }
}

.em {
  width: 100%;
  height: 207rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  padding: 0;
  margin: 0;
}

button::after {
  border: none;
}

.option {
  .op-list {

    .op-box {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
       justify-content: space-between;
      .b-item:last-child {
        margin-right: 0;
      }
      .b-item:first-child {
        margin-left: 0;
      }
      .b-item {
        margin: 0 35rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .icon {
          image {
            width: 100rpx;
            height: 100rpx;
            border-radius: 10rpx;
          }
        }

        .n {
          margin-top: -35rpx;
          max-width: 100rpx;
          font-size: 18rpx;
          color: #222222;
        }
      }
      .op-item:first-child {
        margin-left: 0;
      }
      .op-item:nth-child(4) {
        margin-right: 0;
      }
      .op-item:nth-child(5) {
        margin-left: 0;
      }
      .op-item:last-child {
        margin-right: 0;
      }
      .op-item {
        margin: 5rpx 45rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        flex-wrap: wrap;
        max-width: 102rpx;
        width: 102rpx;
        .icon {
          image {
            width: 82rpx;
            height: 72rpx;
            border-radius: 10rpx;
          }
        }

        .n {
          max-width: 102rpx;
          font-size: 20rpx;
        }
      }
    }
  }
}


.top-box {
  padding-left: 30rpx;
  box-sizing: border-box;

  .left {
    .name {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #222222;
      margin-right: 8rpx;
      // max-width: 100rpx;
    }

    .icon {
      image {
        width: 20rpx;
        height: 20rpx;
      }
    }
  }

  .middle {
    margin-left: 10rpx;

    .ipt {
      position: relative;

      input {
        width: 290rpx;
        height: 60rpx;
        background: #F6F6F6;
        border-radius: 12rpx;
        padding: 0 0 0 20rpx;
      }

      .icon {
        image {
          position: absolute;
          left: 85%;
          top: 50%;
          transform: translate(0, -50%);
          width: 50rpx;
          height: 50rpx;
        }
      }
    }

  }

  .right {
    margin-left: 15rpx;
    width: 60rpx;
    height: 60rpx;

    .share {
      width: 60rpx;
      height: 60rpx;
      background: #F6F6F6;
      border-radius: 12rpx;

      image {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }

}

.content {
  padding: 10rpx 30rpx 0 30rpx;

  .swiper {

    image {
      width: 690rpx;
      height: 220rpx;
      border-radius: 12rpx;
    }
  }

  .option {
    image {
      width: 90rpx;
      height: 90rpx;
    }
  }

  .notice {
    padding: 20rpx 30rpx;
    overflow: hidden;
    background-color: #e85b50;
    height: 30rpx;
    border-radius: 15rpx;
    margin: 10rpx 0;

    :deep(.nut-swiper) {
      height: 35rpx;
    }

    .desc {

      .left {
        .text {
          color: #fff;
          font-size: 24rpx;
        }
      }

      .right {
        padding: 5rpx 20rpx;
        font-size: 30rpx;
        border: 1rpx solid #FFF6C7;
        border-radius: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 900;
        color: #fbf6e2;

        image {
          width: 263rpx;
          height: 36rpx;
          padding: 0 10rpx;
        }
      }
    }
  }


  .project:first-child {
    margin-right: 20rpx;
  }

  .p {
    margin-top: 20rpx;

    .pro-item {
      margin-top: 20rpx;

      .item {
        max-width: 210rpx !important;

        .avatar {
          image {
            width: 210rpx !important;
            height: 120rpx !important;
            border-radius: 10rpx;
          }
        }


        .p-price {
          color: #e85b50;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: 500;
          font-size: 26rpx;
          color: #FB4E47;
        }
      }
    }
  }


  .project {
    flex: 1;
    margin-top: 20rpx;

    .pro-item {
      margin-top: 20rpx;


      .item {
        max-width: 162rpx;

        .avatar {
          image {
            width: 162rpx;
            height: 136rpx;
            border-radius: 10rpx;
          }
        }

        .p-name {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: 400;
          font-size: 20rpx;
          color: #111111;
        }
      }
    }

    .title-box {
      .t-left {
        .line {
          margin-right: 10rpx;
          width: 8rpx;
          height: 24rpx;
          background: radial-gradient(#FB4E47 0%, #FFFFFF 100%);
          border-radius: 4rpx 4rpx 4rpx 4rpx;
        }

        .t-name {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 28rpx;
          color: #222222;
        }
      }


      .t-right {
        .t-more {
          color: #e85b50;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 20rpx;
          color: #FB4E47;
        }
      }
    }
  }
}
</style>
